package com.datatest.riskcheck.tools;



import com.datatest.beans.vo.SendEmailMessageVO;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;


public class EmailUtil
{
	
	public static void main(String[] args) throws Exception {
		EmailUtil dd = new EmailUtil("lxt@jccfc.com","85250195Star");
		Properties p = setSMTP("smtp.exmail.qq.com", "25", false, false);
		
		SendEmailMessageVO vo = new SendEmailMessageVO(new String[]{"luolan@jccfc.com","wangp@jccfc.com","hush@jccfc.com"}, "test", "下班了，请记得打卡哦，机会只有一次，错过打卡，两眼泪汪汪");
		vo.setCcAddress("lxt@jccfc.com");
		vo.setFormAddress("lxt@jccfc.com");
		vo.setContextType("text/html;charset=UTF-8");

       /* File path = null;
            path = new File(ResourceUtils.getURL("classpath:").getPath());
            if (!path.exists()) {
                path = new File("");
            }
            File downloadPath = new File(path.getAbsolutePath(), "static/download/");
            File[] files = downloadPath.listFiles();
            String fileName = null;
            if (files != null) {
                for (int i = 0; i < files.length; i++) {
                    fileName = files[i].getName();
                }
            }
        dd.sendMail(p, vo,downloadPath+"/"+fileName);*/
       dd.sendMail2(p,vo);
	}
	

    private String username = null; // 邮箱用户名

    private String password = null; // 邮箱密码
    /**
     * 
     * 传入自己的邮箱用户名和密码
     * 
     * @param username
     * 
     * @param password
     */

    public EmailUtil(String username, String password)
    {

        this.username = username;

        this.password = password;

    }

    /**
     * 发送邮件
     * 
     * @param props
     *            配置信息
     * @param sem
     *            发送邮件实体
     * @throws Exception
     *             异常
     */
    public void sendMail(Properties props, SendEmailMessageVO sem, String path) throws Exception {

        try {
            Session session = createSession(props);
            // 创建邮件对象
            MimeMessage message = new MimeMessage(session);
            message.setFrom(InternetAddress.parse(MimeUtility.decodeText(sem.getFormAddress()))[0]);

            // TO为初级收件人，CC为邮件副本抄送，BCC应该是密秘抄送吧
            final int num = sem.getToAddress().length;
            InternetAddress to_Adress[] = new InternetAddress[num];
            for (int i = 0; i <num ; i++) {
                 to_Adress[i] = new InternetAddress(sem.getToAddress()[i]);
            }
            //邮件收件人
            message.setRecipients(MimeMessage.RecipientType.TO, to_Adress);
            //邮件抄送人
            message.setRecipient(Message.RecipientType.CC, new InternetAddress(sem.getCcAddress()));
            //邮件主题
            message.setSubject(MimeUtility.encodeText(sem.getSubject(), "UTF-8", "B"));

            //向multipart对象中添加邮件的各个部分内容，包括文本内容和附件
            Multipart multipart = new MimeMultipart();
            //设置附件内容
            MimeBodyPart bodyPart = new MimeBodyPart();
            File file = new File(path);
            //要发送附件的路径
            FileDataSource fileDataSource = new FileDataSource(file);
            //添加附件
            bodyPart.setDataHandler(new DataHandler(fileDataSource));
            // 处理附件名称中文（附带文件路径）乱码问题
            bodyPart.setFileName(MimeUtility.encodeText(file.getName()));
            MimeBodyPart textBodyPart = new MimeBodyPart();
            textBodyPart.setText(sem.getContext());
            multipart.addBodyPart(textBodyPart,0);
            multipart.addBodyPart(bodyPart,1);

            message.setContent(multipart);
            message.setSentDate(new Date());
            //message.setContent(sem.getContext(), sem.getContextType());

            // 发送消息
            Transport.send(message);
        } catch (AddressException e) {
            e.printStackTrace();
            throw new Exception("邮箱格式不正确");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new Exception("发送内容编码不正确");
        }catch (AuthenticationFailedException e){
            if(e.getMessage().indexOf("454")!=-1) {
                throw new Exception("您设置的邮件没有开启SMTP服务");
            } else if(e.getMessage().indexOf("535")!=-1) {
                throw new Exception("无权连接到您设置的邮箱，可能邮箱和密码不匹配");
            } else {
                throw new Exception(e.getMessage());
            }
        } catch (MessagingException e) {
            e.printStackTrace();
            throw new Exception(e.getMessage());
        }

    }
    public void sendMail2(Properties props, SendEmailMessageVO sem) throws Exception {

        try {
            Session session = createSession(props);
            // 创建邮件对象
            MimeMessage message = new MimeMessage(session);
            message.setFrom(InternetAddress.parse(MimeUtility.decodeText(sem.getFormAddress()))[0]);

            // TO为初级收件人，CC为邮件副本抄送，BCC应该是密秘抄送吧
            final int num = sem.getToAddress().length;
            InternetAddress to_Adress[] = new InternetAddress[num];
            for (int i = 0; i <num ; i++) {
                to_Adress[i] = new InternetAddress(sem.getToAddress()[i]);
            }
            //邮件收件人
            message.setRecipients(MimeMessage.RecipientType.TO, to_Adress);
            //邮件抄送人
            message.setRecipient(Message.RecipientType.CC, new InternetAddress(sem.getCcAddress()));
            //邮件主题
            message.setSubject(MimeUtility.encodeText(sem.getSubject(), "UTF-8", "B"));

            //向multipart对象中添加邮件的各个部分内容，包括文本内容和附件
            Multipart multipart = new MimeMultipart();
            MimeBodyPart textBodyPart = new MimeBodyPart();
            textBodyPart.setText(sem.getContext());
            multipart.addBodyPart(textBodyPart,0);


            message.setContent(multipart);
            message.setSentDate(new Date());
            //message.setContent(sem.getContext(), sem.getContextType());

            // 发送消息
            Transport.send(message);
        } catch (AddressException e) {
            e.printStackTrace();
            throw new Exception("邮箱格式不正确");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new Exception("发送内容编码不正确");
        }catch (AuthenticationFailedException e){
            if(e.getMessage().indexOf("454")!=-1) {
                throw new Exception("您设置的邮件没有开启SMTP服务");
            } else if(e.getMessage().indexOf("535")!=-1) {
                throw new Exception("无权连接到您设置的邮箱，可能邮箱和密码不匹配");
            } else {
                throw new Exception(e.getMessage());
            }
        } catch (MessagingException e) {
            e.printStackTrace();
            throw new Exception(e.getMessage());
        }

    }

    /**
     * 创建连接会话
     * 
     * @param props
     * @return
     */
    Session createSession(Properties props)
    {
        Session session = Session.getInstance(props, new Authenticator()
        {
            // 返回用户名密码认证
            @Override
            public PasswordAuthentication getPasswordAuthentication()
            {
                PasswordAuthentication pa = new PasswordAuthentication(username, password);
                return pa;
            }
        });
        return session;
    }

    /**
     * 设置SMTP默认配置
     * 
     * @param host
     *            发件服务器
     * @param port
     *            端口
     * @return 属性配置
     */
    public static Properties setSMTP(String host, String port, boolean ssl,boolean isGmail)
    {
        Properties p = new Properties();
        p.setProperty("mail.smtp.host", host); // 按需要更改
        p.setProperty("mail.smtp.protocol", "smtp");
        p.setProperty("mail.smtp.port", port);
        p.setProperty("mail.smtp.auth", "true");
        System.setProperty("mail.mime.splitlongparameters", "false");
        System.setProperty("mail.mime.charset", "UTF-8");
        // SSL安全连接参数
        /*
         * if(ssl){ p.setProperty("mail.smtp.socketFactory.class",
         * "javax.net.ssl.SSLSocketFactory"); }
         */
        if(!isGmail){
            p.setProperty("mail.smtp.socketFactory.fallback", "false");
            p.setProperty("mail.smtp.socketFactory.port", port);
        }else{
            p.setProperty("mail.smtp.starttls.enable", "true"); 
        }
        return p;
    }

}
